package com.library.framework.web.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.library.common.core.domain.model.UnionUser;
import com.library.books.domain.Student;
import com.library.books.service.IStudentService;
import com.library.common.core.domain.entity.SysUser;
import com.library.common.core.domain.model.LoginUser;
import com.library.common.enums.UserStatus;
import com.library.system.service.ISysUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Collections;

/**
 * 用户验证处理
 *
 * @author ruoyi
 */
@Service("wechatAccountDetailsService")
public class WechatAccountDetailsServiceImpl implements UserDetailsService {

    private static final Logger log = LoggerFactory.getLogger(WechatAccountDetailsServiceImpl.class);

    @Resource
    private IStudentService studentService;

    @Resource
    private ISysUserService userService;

    @Override
    @Transactional(rollbackFor = Exception.class , isolation = Isolation.READ_COMMITTED)
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        /// 暂不需要
//        Map param = JSON.parseObject(username, Map.class);
//        String name = (String) param.get("username");
//        String pass = (String) param.get("password");

        // 登录
        SysUser user = login(username);
        // token信息
        return createLoginUser(user);
    }

    /** 创建登陆用户信息-微信小程序默认没有角色权限 */
    public UserDetails createLoginUser(SysUser user) {
        return new LoginUser(user.getUserId(),null,user, Collections.emptySet());
    }

    /**
     * 登陆
     *  - 学号登陆
     *  - 用户登陆
     * @param name 登录账号/编号
     */
    private SysUser login(String name) {
        // 联合查询
        UnionUser unionUser = userService.selectUnionUser(name);
        if(unionUser == null) {
            log.error("用户不存在[{}]",unionUser);
            throw new RuntimeException("登陆失败，信息不存在");
        }
        // 填充数据
        if(UnionUser.TABLE.STUDENT.equals(unionUser.getTable())) {
            return student(unionUser);
        }
        else {
            return sysUser(unionUser);
        }
    }

//    /**
//     * 登陆
//     *  - 学号登陆
//     *  - 用户登陆
//     * @param name 登录账号/编号
//     * @param pass 登录密码
//     */
//    private SysUser login(String name, String pass) {
//        // 联合查询
//        UnionUser unionUser = userService.selectUnionUser(name);
//        if(unionUser == null) {
//            log.error("用户不存在[{}]",unionUser);
//            throw new RuntimeException("登陆失败，信息不存在");
//        }
//        // 填充数据
//        if(UnionUser.TABLE.STUDENT.equals(unionUser.getTable())) {
//            return student(unionUser,pass);
//        }
//        else {
//            return sysUser(unionUser,pass);
//        }
//    }

    /**
     * 学生登陆
     * @param union 登录数据
     */
    private SysUser student(UnionUser union) {
        // 学生学籍信息
        Student student = studentService.getOne(new LambdaQueryWrapper<Student>()
            .eq(Student::getStudentNumber, union.getUserNumber())
        );
        return new SysUser()
            .setUserNumber(student.getStudentNumber())
            // 密码是身份证后六位
            .setPassword(student.getStudentIdCard().substring(student.getStudentIdCard().length() - 6))
            .setNickName(student.getStudentNick())
            .setAvatar(student.getStudentHeadPic())
            .setSex(student.getStudentSex())
            .setPhonenumber(student.getStudentNumber())
        ;

//        // 检查密码是否正确（身份证后六位）
//        String idCard = student.getStudentIdCard().substring(student.getStudentIdCard().length() - 6);
//        if(! idCard.equals(pass)) {
//            log.error("密码错误[{}]",pass);
//            throw new RuntimeException("登陆失败，密码错误");
//        }
//        // 学生基本信息
//        StudentBasic studentBasic = new StudentBasic(
//            student.getStudentId(),
//            student.getStudentNumber(),
//            student.getStudentName(),
//            student.getStudentNick(),
//            student.getStudentSex(),
//            student.getStudentDorm(),
//            student.getStudentClass(),
//            student.getStudentPhoneNumber(),
//            student.getStudentHeadPic()
//        );
        /// 避免习惯性调用问题，将学生信息填充到常用数据里
        // SecurityUtils.getLoginUser().getUser().getUserNumber()
//        return studentBasic.toSysUser();
    }

    /**
     * 系统用户登陆
     * @param unionUser 系统用户名 / 系统用户编号
     */
    private SysUser sysUser(UnionUser unionUser) {
        SysUser user = userService.selectUserByNumber(unionUser.getUserNumber());
        if (UserStatus.DELETED.getCode().equals(user.getDelFlag())) {
            log.info("登录用户：{} 已被删除.", unionUser.getUserNumber());
            throw new RuntimeException("登陆失败，信息不存在");
        } else if (UserStatus.DISABLE.getCode().equals(user.getStatus())) {
            log.info("登录用户：{} 已被停用.", unionUser.getUserNumber());
            throw new RuntimeException("登陆失败，信息不存在");
        }
//        else if(! SecurityUtils.matchesPassword(pass,user.getPassword())) {
//            throw new RuntimeException("登陆失败，密码错误");
//        }
        // 返回用户信息
        return user;
    }

}
